<template>
  <div>
    <!--
      必填:
      action 上传地址, 因为用腾讯云, 所以用 # 代替
      file-list 用来管理图片

      list-type 控制样式
      :class 动态样式控制上传按钮显示

      on-preview 绑定后会显示放大镜, 点击后的弹窗回调需要另外写
     -->
    <!-- 上传图片 -->
    <el-upload
      action="#"
      :file-list="fileList"

      list-type="picture-card"
      :class="{disable: fileList.length>0}"

      :on-preview="preview"
      :on-remove="onRemove"
      :on-change="onChange"

      :http-request="upload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <!-- 进度条组件 -->
    <el-progress
      v-if="showProgress"
      :text-inside="true"
      :stroke-width="26"
      :percentage="percentage"
      style="width:146px"
    />
    <el-dialog title="预览" :visible="showDialog" @close="showDialog = false">
      <el-row type="flex" justify="center">
        <img :src="imgUrl" alt="">
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDMXS7VcFivrWu1rQijTv61g5D4fz1mGTP',
  SecretKey: 'g6F7h02nIWUBcleGadPv97nDMDo8BxRe'
})
export default {
  data() {
    return {
      fileList: [

      ],
      showDialog: false,
      imgUrl: '',
      percentage: 0,
      showProgress: false
    }
  },
  methods: {
    preview(file) {
      // 每当点击,都可以获取到当前点击的图片对象
      console.log(file)
      this.imgUrl = file.url
      this.showDialog = true
    },
    onRemove(file, fileList) {
      this.fileList = fileList
    },
    onChange(file, fileList) {
      this.fileList = fileList
    },
    upload(params) {
      console.log(params)
      this.showProgress = true
      cos.putObject({
        Bucket: 'hr66wx-1307452180', /* 存储桶名称 */
        Region: 'ap-guangzhou', /* 存储桶所在地域 */
        Key: params.file.name, /* 文件名 */
        StorageClass: 'STANDARD', /* 不改 */
        Body: params.file, // 上传文件对象
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          // 注意this指向
          this.percentage = progressData.percent * 100
          console.log(86, this.percentage)
        }
      }, (err, data) => {
        console.log(err || data)
        if (!err) {
          this.fileList[0].url = `https://${data.Location}`
          this.fileList[0].status = 'success'
        }
        setTimeout(() => {
          this.showProgress = false
        }, 1000)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.disable {
  // /deep/ .el-upload--picture-card {
  ::v-deep .el-upload--picture-card {
    display: none;
  }
}
</style>
